package com.example.meitu.api.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.meitu.api.common.UserLoginContextHolder;
import com.example.meitu.api.domain.Media;
import com.example.meitu.api.domain.MediaAccount;
import com.example.meitu.api.domain.UnionMediaSub;
import com.example.meitu.api.dto.SearchMediaDTO;
import com.example.meitu.api.service.MediaAccountService;
import com.example.meitu.api.service.MediaService;
import com.example.meitu.api.dao.MediaMapper;
import com.example.meitu.api.service.UnionMediaSubService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 蔡超
* @description 针对表【mt_media(媒体表)】的数据库操作Service实现
* @createDate 2024-06-27 15:26:06
*/
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media>
    implements MediaService{

    @Resource
    private MediaAccountService mediaAccountService;

    @Resource
    private UnionMediaSubService unionMediaSubService;

    /**
     * //把所有的媒体都放放在内存中 mediaMap {mediaName:mediaId}
     * //把所有的账号都放到内存    accountMao {accountMap:accountId}
     *
     * @param keyword
     * @return
     */
    @Override
    public List<SearchMediaDTO> searchMedia(String keyword) {

        //全部的媒体信息
        Map<Integer,Media> mediaMap = list().stream()
                .collect(Collectors.toMap(Media::getId,
                        each->each,
                        (value1, value2) -> value1)
                        );


        List<SearchMediaDTO> result = new ArrayList<>();
        //有权限的品牌 + 竞品
        //TODO 需要有权限校验，目前只有登录人的有权限的品牌，但是很多校验需要用到媒体id,不知道该怎么校验了
//        List<Integer> permissionBrands = UserLoginContextHolder.get().getPermissionBrands();

        Map<Integer, Media> MediaMap = allMedia();
        //查询媒体账号
        QueryWrapper<MediaAccount> queryWrapper = new QueryWrapper();
        queryWrapper.select("account_name, media_id,platform")
                    .lambda()
                    .like(MediaAccount::getAccountName, keyword)
//                    .in(MediaAccount::getMediaId, permissionBrands)
                    .groupBy(MediaAccount::getAccountName)
                    .orderByAsc(MediaAccount::getId)
                    .last(" limit 5 ");
        List<MediaAccount> accountList = mediaAccountService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(accountList)) {
            result = accountList.stream().map(account ->{
                SearchMediaDTO searchMediaDTO = new SearchMediaDTO();
                searchMediaDTO.setMediaId(account.getMediaId());
                searchMediaDTO.setMediaName(MediaMap.get(account.getMediaId()).getMediaName());
                searchMediaDTO.setPlatform(account.getPlatform());
                searchMediaDTO.setAccountName(account.getAccountName());
                searchMediaDTO.setSubUnionId(mediaMap.get(account.getMediaId()).getSubUnionMediaId());
                searchMediaDTO.setSubUnionName(mediaMap.get(account.getMediaId()).getSubUnionMediaName());
                return searchMediaDTO;
            }).collect(Collectors.toList());
        }

        List<Integer> accountMediaId = accountList.stream().map(MediaAccount::getMediaId).collect(Collectors.toList());

        if (result.size() == 5) {
            return result;
        } else {
            List<SearchMediaDTO> mediaResult = new ArrayList<>();
            int remain = 5 - result.size();

            //查询子媒归类名称
            LambdaQueryWrapper<UnionMediaSub> lambdaQueryWrappe = new LambdaQueryWrapper();
            lambdaQueryWrappe.like(UnionMediaSub::getUnionMediaName, keyword);
            lambdaQueryWrappe.eq(UnionMediaSub::getDelFlag, '0');
            lambdaQueryWrappe.orderByAsc(UnionMediaSub::getSubUnionId);
            lambdaQueryWrappe.last(" limit  " + remain);
            List<UnionMediaSub> unionMediaSubs = unionMediaSubService.list(lambdaQueryWrappe);
            if (CollectionUtil.isNotEmpty(unionMediaSubs)) {
                remain = 5 - unionMediaSubs.size();

                List<SearchMediaDTO> list2 = unionMediaSubs.stream().map(unionMediaSub -> {
                    SearchMediaDTO searchMediaDTO = new SearchMediaDTO();
//                    searchMediaDTO.setMediaId(unionMediaSub.getUnionMediaId());
//                    searchMediaDTO.setMediaName(unionMediaSub.getUnionMediaName());
                    searchMediaDTO.setSubUnionId(unionMediaSub.getSubUnionId());
                    searchMediaDTO.setSubUnionName(unionMediaSub.getSubUnionName());
                    return searchMediaDTO;
                }).collect(Collectors.toList());
                result.addAll(list2);
            }

            if  (remain <= 0) {
                return result;
            }

            //查询媒体名称
            LambdaQueryWrapper<Media> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.like(Media::getMediaName,keyword);
//            lambdaQueryWrapper.in(Media::getId, permissionBrands);
            if (CollectionUtil.isNotEmpty(accountMediaId)) {
                lambdaQueryWrapper.notIn(Media::getId, accountMediaId);
            }
            lambdaQueryWrapper.orderByAsc(Media::getId);
            lambdaQueryWrapper.last(" limit  " + remain);
            List<Media> list = this.list(lambdaQueryWrapper);
            if (CollectionUtil.isNotEmpty(list)) {
                //返回前5个品牌
                List<SearchMediaDTO> list3 = list.stream().map(media -> {
                    SearchMediaDTO searchMediaDTO = new SearchMediaDTO();
                    searchMediaDTO.setMediaId(media.getId());
                    searchMediaDTO.setMediaName(media.getMediaName());
                    searchMediaDTO.setSubUnionId(mediaMap.get(media.getId()).getSubUnionMediaId());
                    searchMediaDTO.setSubUnionName(mediaMap.get(media.getId()).getSubUnionMediaName());
                    return searchMediaDTO;
                }).collect(Collectors.toList());
                result.addAll(list3);
            }
            return result;
        }

    }

    @Override
    public Map<Integer, Media> allMedia() {
        LambdaQueryWrapper<Media> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(Media::getDelFlag, '0');
        List<Media> list = list(lambdaQueryWrapper);
        Map<Integer, Media> result = list.stream()
                .collect(Collectors.toMap(Media::getId, media -> media, (k1, k2) -> k1));
        return result;
    }

    @Override
    public List<Media> getMediaListByUnionId(Integer unionId) {
        LambdaQueryWrapper<Media> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Media::getUnionMediaId, unionId);
        lambdaQueryWrapper.eq(Media::getDelFlag, '0');
        List<Media> list = list(lambdaQueryWrapper);
        return list;
    }

    @Override
    public Integer size() {
        return this.count();
    }
}




